package cc.messcat.web.filter;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.service.system.UserService;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class UrlFilter extends PathMatchingFilter {


	@Autowired
	protected UserService userService;

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		response.setContentType("application/json;charset=utf-8");
		try (ServletOutputStream out = response.getOutputStream()) {
			String requestURI = getPathWithinApplication(request);
			System.out.println("requestURI:" + requestURI);

			ResponseBean bean = new ResponseBean(CommonConstant.EXCEPTION_CODE_600);
			JSONObject jsonObject = JSONObject.fromObject(bean);
			if (requestURI.length() - 2 == requestURI.lastIndexOf("/")) {
				requestURI = requestURI.substring(0, requestURI.lastIndexOf("/"));
			}
			boolean permit = subject.isPermitted(requestURI);
			if (!permit) {
				out.print(jsonObject.toString());
			}
			System.out.println(permit);
			return permit;
		} catch (Exception e) {
			ServletOutputStream out = response.getOutputStream();
			ResponseBean bean = new ResponseBean(CommonConstant.EXCEPTION_CODE_600);
			JSONObject jsonObject = JSONObject.fromObject(bean);
			out.print(jsonObject.toString());
			return false;
		}
	}

}
